package com.ruoyi.system.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysSupplierModuleType;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysSupplierModuleTypeService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;

/**
 * 模块类型Controller
 * 
 * @author ruoyi
 * @date 2022-05-07
 */
@RestController
@RequestMapping("/system/module/type")
public class SysSupplierModuleTypeController extends BaseController
{


    @Autowired
    private ISysSupplierModuleTypeService typeService;

    /**
     * 获取模块类型列表
     */
    //@PreAuthorize("@ss.hasPermi('system:type:list')")
    @GetMapping("/list")
    public AjaxResult list(SysSupplierModuleType type)
    {
        List<SysSupplierModuleType> types = typeService.selectSupplierModuleTypeList(type);
        return AjaxResult.success(types);
    }

    /**
     * 查询模块类型列表（排除节点）
     */
    //@PreAuthorize("@ss.hasPermi('system:type:list')")
    @GetMapping("/list/exclude/{typeId}")
    public AjaxResult excludeChild(@PathVariable(value = "typeId", required = false) Long typeId)
    {
        List<SysSupplierModuleType> types = typeService.selectSupplierModuleTypeList(new SysSupplierModuleType());
        Iterator<SysSupplierModuleType> it = types.iterator();
        while (it.hasNext())
        {
            SysSupplierModuleType d = (SysSupplierModuleType) it.next();
            if (d.getTypeId().intValue() == typeId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), typeId + ""))
            {
                it.remove();
            }
        }
        return AjaxResult.success(types);
    }

    /**
     * 根据模块类型编号获取详细信息
     */
   // @PreAuthorize("@ss.hasPermi('system:type:query')")
    @GetMapping(value = "/{typeId}")
    public AjaxResult getInfo(@PathVariable Long typeId)
    {
        typeService.checkSupplierModuleTypeDataScope(typeId);
        return AjaxResult.success(typeService.selectSupplierModuleTypeById(typeId));
    }



    /**
     * 获取模块类型下拉树列表
     */
  @GetMapping("/treeselect/{typeId}")
    public AjaxResult treeselect(@PathVariable Long typeId)
    {
        SysSupplierModuleType type=new SysSupplierModuleType();
        type.setTypeId(typeId);
        List<SysSupplierModuleType> types = typeService.selectSupplierModuleTypeList(type);
        return AjaxResult.success(typeService.buildSupplierModuleTypeTreeSelect(types));
    }

    /**
     * 获取模块类型下拉树列表
     */
   @GetMapping("/treeselect")
    public AjaxResult treeselect(SysSupplierModuleType type)
    {
        List<SysSupplierModuleType> types = typeService.selectSupplierModuleTypeList(type);
        return AjaxResult.success(typeService.buildSupplierModuleTypeTreeSelect(types));
    }

    /**
     * 加载对应角色模块类型列表树
     */
    @GetMapping(value = "/roleSupplierModuleTypeTreeselect/{roleId}")
    public AjaxResult roleSupplierModuleTypeTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<SysSupplierModuleType> types = typeService.selectSupplierModuleTypeList(new SysSupplierModuleType());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("types", typeService.buildSupplierModuleTypeTreeSelect(types));
        return ajax;
    }

    /**
     * 新增模块类型
     */
   // @PreAuthorize("@ss.hasPermi('system:type:add')")
    @Log(title = "模块类型管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysSupplierModuleType type)
    {
        if (UserConstants.NOT_UNIQUE.equals(typeService.checkSupplierModuleTypeNameUnique(type)))
        {
            return AjaxResult.error("新增模块类型'" + type.getTypeName() + "'失败，模块类型名称已存在");
        }
        type.setCreateBy(getUsername());
        return toAjax(typeService.insertSupplierModuleType(type));
    }

    /**
     * 新增模块类型
     */
   // @PreAuthorize("@ss.hasPermi('system:type:add')")
    @Log(title = "模块类型管理", businessType = BusinessType.INSERT)
    @PostMapping("/addRootType")
    public AjaxResult addRootType(@Validated @RequestBody SysSupplierModuleType type)
    {
        type.setCreateBy(getUsername());
        return toAjax(typeService.inserRootType(type));
    }




    /**
     * 修改模块类型
     */
 //   @PreAuthorize("@ss.hasPermi('system:type:edit')")
    @Log(title = "模块类型管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysSupplierModuleType type)
    {
        Long typeId = type.getTypeId();
        typeService.checkSupplierModuleTypeDataScope(typeId);
        if (UserConstants.NOT_UNIQUE.equals(typeService.checkSupplierModuleTypeNameUnique(type)))
        {
            return AjaxResult.error("修改模块类型'" + type.getTypeName() + "'失败，模块类型名称已存在");
        }
        else if (type.getParentId().equals(typeId))
        {
            return AjaxResult.error("修改模块类型'" + type.getTypeName() + "'失败，上级模块类型不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, type.getStatus()) && typeService.selectNormalChildrenSupplierModuleTypeById(typeId) > 0)
        {
            return AjaxResult.error("该模块类型包含未停用的子模块类型！");
        }
        type.setUpdateBy(getUsername());
        return toAjax(typeService.updateSupplierModuleType(type));
    }

    /**
     * 删除模块类型
     */
   // @PreAuthorize("@ss.hasPermi('system:type:remove')")
    @Log(title = "模块类型管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{typeId}")
    public AjaxResult remove(@PathVariable Long typeId)
    {
        if (typeService.hasChildBySupplierModuleTypeById(typeId))
        {
            return AjaxResult.error("存在下级模块类型,不允许删除");
        }
        if (typeService.checkSupplierModuleTypeExistQuestion(typeId))
        {
            return AjaxResult.error("模块类型存在用户,不允许删除");
        }
        typeService.checkSupplierModuleTypeDataScope(typeId);
        return toAjax(typeService.deleteSupplierModuleTypeById(typeId));
    }
}
